package com.yearner.reviewplan.user;

import com.google.gson.Gson;
import com.yearner.reviewplan.common.util.MyJdbcUtil;
import com.yearner.reviewplan.user.exceptions.UserNotFoundException;
import com.yearner.reviewplan.user.model.*;
import org.springframework.stereotype.Repository;

import java.util.List;
import static com.yearner.reviewplan.user.enums.UserTableEnum.*;

/**
 * @author pengyg
 * @since 2019/10/12
 */
@Repository
public class UserRepository extends UserBaseRepository {


    public UserRepository(MyJdbcUtil myJdbcUtil, Gson gson) {
        super(myJdbcUtil, gson);
    }

    void save(User user) {
        String sql = "insert into user values (?,?,?,?) " +
                "ON DUPLICATE KEY UPDATE password=?";
        jdbcTemplate.update(sql,
                user.getUserId().toString(),
                user.getAccountName(),
                user.getPassword(),
                gson.toJson(user.getCycle()),
                user.getPassword());

    }

    public List<User> all() {
        String sql = "select * from user";
        return jdbcTemplate.query(sql, mapper());
    }

    boolean exist(String accountName) {
        String sql = getByOneParamSql(TABLE.getColumn(),ACCOUNT.getColumn());
        List<User> query = jdbcTemplate.query(sql, mapper(), accountName);
        return !query.isEmpty();
    }
    User byId(String id) {
        String sql = getByOneParamSql(TABLE.getColumn(),ID.getColumn());
        List<User> query = jdbcTemplate.query(sql, mapper(), id);
        if (query.isEmpty()) {
            throw new UserNotFoundException(2);
        }
        return query.get(0);
    }


}
